package org.example.algorithm.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class GroupAnagramsSolution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str:strs) {
            int[] arr = new int[26];
            for (int i=0;i<str.length();i++) {
                arr[str.charAt(i) - 'a']++;
            }
            StringBuilder sb = new StringBuilder();
            for (int i=0;i<arr.length;i++) {
                if (arr[i] > 0) {
                    sb.append(i + 'a');
                    sb.append(arr[i]);
                }
            }
            String mapKey = sb.toString();
            List<String> strList = map.getOrDefault(mapKey, new ArrayList<>());
            strList.add(str);
            map.put(mapKey, strList);
        }
        return new ArrayList<>(map.values());
    }

    public List<List<String>> groupAnagrams2(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str: strs) {
            String strKey = getKey(str);
            if (map.containsKey(strKey)) {
                map.get(strKey).add(str);
            } else {
                List<String> newList = new ArrayList<>();
                newList.add(str);
                map.put(strKey, newList);
            }
        }
        return new ArrayList<>(map.values());
    }

    private String getKey(String str) {
        char[] arr = str.toCharArray();
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<arr.length;i++) {
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String[] arr = {"eat", "tea", "tan", "ate", "nat", "bat"};
        GroupAnagramsSolution groupAnagramsSolution = new GroupAnagramsSolution();
        List<List<String>> res = groupAnagramsSolution.groupAnagrams(arr);
        System.out.println(res);
    }
}
